<?php

App::uses('AppController', 'Controller');

class CenovniciController extends AppController {
	
	public $uses = array('Product', 'ProductPrice');
	
	public $paginate = array(
		'limit' => ITEMS_PER_PAGE
	);
    
    public function index() {
	    $this->set('data', $this->Product->getPricelists());
	}
	
	public function _setCommonData($date, $data=false, $reformat=false) {
	    $products = $this->Product->getAllGroupedByType();
	    
	    if ($data && $reformat) {
	        $tmp = array();
	        foreach($data as $row) {
	            $product_id = $row['ProductPrice']['product_id'];
	            $tmp[$product_id] = $row;
	            
	            $product = $this->Product->findById($product_id, 'Product.*');
	            $tmp[$product_id]['Product'] = $product['Product'];
	            $data = $tmp;
	        }
	    }
	    
	    $this->set(compact('data', 'date', 'products'));
	}
	
	public function novi() {
	    $this->_setCommonData(date('Y-m-d'));
	    $this->render('form');
	}
	
	public function obrisi($date) {
	    if($this->ProductPrice->deleteAll(array('effective_date'=>$date), false)) {
	        $this->setFlash('Sve cene definisane ' . local_date($date) . ' su obrisane.', 'ok');
	    }else{
	        $this->setFlash('Brisanje cenovnika nije uspelo.');
	    }
	    
	    $this->redirect('index');
	}
	
	public function izmeni($date) {
	    if($data = $this->Product->getPricelist($date)) {
	        $this->_setCommonData($date, $data);
	        
	        return $this->render('form');
	    }
	    
	    $this->redirect('index');
	}
	
	public function sacuvaj() {
	    if (!empty($this->data)) {
	        $data = $this->data;
	        $date = $data['ProductPrice']['date'];
	        unset($data['ProductPrice']);
	        foreach($data as &$row) {
	            $row['ProductPrice']['effective_date'] = $date;
	        }
	        
	        if($this->ProductPrice->saveAll($data)) {
	            $this->setFlash('Cenovnik je sačuvan.', 'ok');
	            $this->redirect('/cenovnici/izmeni/'.$date);
	        }else{
	            $this->_setCommonData($date, $data, true);
	            $this->set('errors', $this->ProductPrice->validationErrors);
	            $this->setFlash('Čuvanje nije uspelo.<br>Proverite da li ste uneli sve cene.');
	            return $this->render('form');
	        }
	    }
	    
	    $this->redirect('index');
	}
	
}